package org.pms.demo.webservice.service.impl;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.pms.demo.webservice.content.PmsContent;
import org.pms.demo.webservice.service.SessionVersionService;
import org.pms.demo.webservice.utils.DateUtil;
import org.pms.demo.webservice.utils.ProjectUtils;
import org.pms.demo.webservice.vo.SessionInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by laijianpeng on 17/10/16.
 */
@Service
public class SessionVersionServiceImpl implements SessionVersionService{
    @Resource
    private SessionDAO sessionDAO;
    @Override
    public String getSessionList() {
        Collection<Session> sessions =  sessionDAO.getActiveSessions();
        System.out.println(ProjectUtils.beanToJson(sessions));

        List<SessionInfo> sessionInfoList = new ArrayList<>();
        for(Session session:sessions){
            SessionInfo sessionInfo = new SessionInfo();
            sessionInfo.setId(session.getId()+"");
            sessionInfo.setIp_addr(session.getHost());
            sessionInfo.setName((String)session.getAttribute("currentUser"));
            sessionInfo.setLast_access_time(DateUtil.getStringNotNowDate(DateUtil.getDateByTime(session.getLastAccessTime().getTime()),"yyyy-MM-dd HH:mm:ss")+"");
            if(session.getAttribute(PmsContent.SESSION_FORCE_LOGOUT_KEY)!=null)
                sessionInfo.setIsForceLogout((boolean)session.getAttribute(PmsContent.SESSION_FORCE_LOGOUT_KEY));
            sessionInfoList.add(sessionInfo);

        }

        return ProjectUtils.getContentMsg(sessionInfoList);
    }

    @Override
    public String forceLogout(String sessionId) {
        Session session = sessionDAO.readSession(sessionId);
        if(session != null) {
            session.setAttribute(PmsContent.SESSION_FORCE_LOGOUT_KEY, Boolean.TRUE);
        }
        return ProjectUtils.getContentMsg("强制退出成功");
    }
}
